package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;
    /*
    * 处理超时订单 超时订单即待付款单且超过15分钟未付款
    * */
    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    public void processTimeoutOrder(){
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("status",Orders.PENDING_PAYMENT);

        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE,-15);
        Date fifteenMinutesAgo = calendar.getTime();
        queryWrapper.gt("order_time",fifteenMinutesAgo);
        List<Orders> orders = orderMapper.selectList(queryWrapper);
        if(orders!=null&& !orders.isEmpty()){
            orders.forEach(order->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.updateById(order);
            });
        }
    }

    /*
    * 处理一直处于派送中的订单
    * */
    @Scheduled(cron = "0 0 1 * * ? ")//每天凌晨1点触发一次
    public void processDeliveryOrder(){
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("status",Orders.DELIVERY_IN_PROGRESS);
        // 计算一小时之前的时间
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR, -1);
        Date oneHourAgo = cal.getTime();
        // 设置查询条件：记录时间大于一小时之前的时间
        queryWrapper.gt("order_time", oneHourAgo);
        List<Orders> orders = orderMapper.selectList(queryWrapper);
        if(orders!=null&& !orders.isEmpty()){
            orders.forEach(order->{
                order.setStatus(Orders.COMPLETED);
                orderMapper.updateById(order);
            });
        }
    }
}
